package common.Util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by lxl on 2015/10/30.
 */
public class MD5Util {

    public final static String toMD5( String username){

        MessageDigest messageDigest = null ;

        try {

            messageDigest =  MessageDigest.getInstance("MD5") ;

            messageDigest.reset();

            messageDigest.update(username.getBytes("UTF-8"));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();

            return null ;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

            return null ;

        }

        byte[] bytes = messageDigest.digest() ;

        StringBuffer buffer = new StringBuffer() ;

        for( int i = 0 ; i < bytes.length ; i++){

            if( Integer.toHexString(0xFF &  bytes[i]).length() == 1 ){

                buffer.append("0").append(Integer.toHexString( 0xff & bytes[i])) ;

            }
            else {

                buffer.append(Integer.toHexString(0xff & bytes[i])) ;

            }

        }

        return  buffer.toString() ;

    }

}
